<template>
  <div class="bg-white rounded-lg shadow-sm p-6">
    <!-- 页面标题和添加按钮 -->
    <div class="flex items-start justify-between mb-6">
      <div>
        <h2 class="text-2xl font-bold text-gray-900 mb-2">收货地址管理</h2>
        <p class="text-sm text-gray-500">管理您的收货地址，方便快捷下单</p>
      </div>
      <button @click="openCreate" class="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
        <span>添加新地址</span>
      </button>
    </div>

    <!-- 地址列表 -->
    <div class="space-y-4">
      <div v-for="(addr, idx) in addresses" :key="addr.id" :class="[ 'rounded-lg p-4', addr.isDefault ? 'border-2 border-blue-500' : 'border border-gray-200 hover:border-gray-300 transition-colors']">
        <div class="flex items-start justify-between mb-3">
          <div class="flex items-center gap-2">
            <span v-if="addr.isDefault" class="px-3 py-1 bg-blue-600 text-white text-sm rounded">默认地址</span>
            <span class="font-medium text-gray-900">{{ addr.name }}</span>
          </div>
          <span class="text-gray-600">{{ addr.phone }}</span>
        </div>
        <p class="text-gray-700 mb-3">{{ addr.fullAddress }}</p>
        <div class="flex items-center gap-4">
          <button v-if="!addr.isDefault" @click="setDefault(idx)" class="text-blue-600 hover:text-blue-700 text-sm">设为默认</button>
          <button @click="openEdit(idx)" class="text-blue-600 hover:text-blue-700 text-sm">编辑</button>
          <button @click="remove(idx)" class="text-red-600 hover:text-red-700 text-sm">删除</button>
        </div>
      </div>
    </div>

    <!-- 弹窗：新增/编辑地址 -->
    <div v-if="showModal" style="position:fixed; inset:0; background:rgba(0,0,0,.45); display:flex; align-items:center; justify-content:center; z-index:1000;">
      <div class="bg-white rounded-lg shadow-lg w-[520px] max-w-[92%] p-5">
        <div class="flex items-center justify-between mb-3">
          <h3 class="text-lg font-semibold">{{ editingIndex === -1 ? '添加新地址' : '编辑地址' }}</h3>
          <button @click="closeModal" class="text-gray-500 hover:text-gray-700 text-xl">×</button>
        </div>
        <div class="grid grid-cols-1 gap-3">
          <div>
            <label class="block text-sm text-gray-700 mb-1">收件人</label>
            <input v-model="form.name" class="w-full px-3 py-2 border border-gray-300 rounded" placeholder="请输入收件人姓名" />
          </div>
          <div>
            <label class="block text-sm text-gray-700 mb-1">手机号</label>
            <input v-model="form.phone" class="w-full px-3 py-2 border border-gray-300 rounded" placeholder="请输入手机号" />
          </div>
          <div>
            <label class="block text-sm text-gray-700 mb-1">地址</label>
            <input v-model="form.fullAddress" class="w-full px-3 py-2 border border-gray-300 rounded" placeholder="请输入详细地址，如：3号宿舍楼502室" />
          </div>
          <label class="inline-flex items-center gap-2 text-sm text-gray-700 mt-1">
            <input type="checkbox" v-model="form.isDefault" /> 设为默认地址
          </label>
        </div>
        <div class="flex justify-end gap-2 mt-4">
          <button @click="closeModal" class="px-4 py-2 border rounded">取消</button>
          <button @click="save" class="px-4 py-2 bg-blue-600 text-white rounded">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'OrderAddress',
  data() {
    return {
      addresses: [],
      showModal: false,
      editingIndex: -1,
      form: { id: null, name: '', phone: '', fullAddress: '', isDefault: false }
    }
  },
  mounted() {
    this.load()
  },
  methods: {
    storageKey() {
      const uid = localStorage.getItem('userId') || 'guest'
      return `addresses_user_${uid}`
    },
    async load() {
      const uid = localStorage.getItem('userId')
      if (!uid) { this.addresses = []; return }
      try {
        const { data } = await axios.get(`/api/addresses/${uid}`)
        const list = (data && (data.data || data)) || []
        this.addresses = list.map(a => ({
          id: a.id,
          name: a.name,
          phone: a.phone,
          fullAddress: a.full_address,
          isDefault: !!a.is_default
        }))
      } catch (e) {
        console.error('获取地址失败', e)
        this.addresses = []
      }
    },
    persist() {},
    openCreate() {
      this.editingIndex = -1
      this.form = { id: null, name: '', phone: '', fullAddress: '', isDefault: this.addresses.length === 0 }
      this.showModal = true
    },
    openEdit(idx) {
      this.editingIndex = idx
      this.form = { ...this.addresses[idx] }
      this.showModal = true
    },
    closeModal() { this.showModal = false },
    validate() {
      if (!this.form.name.trim()) { alert('请输入收件人'); return false }
      if (!/^\d{7,15}$/.test(this.form.phone.replace(/\D/g,''))) { alert('请输入有效手机号'); return false }
      if (!this.form.fullAddress.trim()) { alert('请输入详细地址'); return false }
      return true
    },
    async save() {
      if (!this.validate()) return
      const uid = localStorage.getItem('userId')
      if (!uid) { alert('请先登录'); return }
      try {
        if (this.editingIndex === -1) {
          await axios.post('/api/addresses', {
            user_id: Number(uid),
            name: this.form.name,
            phone: this.form.phone,
            full_address: this.form.fullAddress,
            is_default: this.form.isDefault ? 1 : 0
          })
        } else {
          await axios.put(`/api/addresses/${this.form.id}`, {
            user_id: Number(uid),
            name: this.form.name,
            phone: this.form.phone,
            full_address: this.form.fullAddress,
            is_default: this.form.isDefault ? 1 : 0
          })
        }
        this.showModal = false
        this.load()
      } catch (e) {
        console.error('保存地址失败', e)
        alert('保存地址失败，请稍后再试')
      }
    },
    async remove(idx) {
      if (!confirm('确认删除该地址？')) return
      try {
        const row = this.addresses[idx]
        await axios.delete(`/api/addresses/${row.id}`)
        await this.load()
      } catch (e) {
        console.error('删除地址失败', e)
        alert('删除地址失败，请稍后再试')
      }
    },
    async setDefault(idx) {
      const uid = localStorage.getItem('userId')
      try {
        const row = this.addresses[idx]
        await axios.put(`/api/addresses/${row.id}/default`, { user_id: Number(uid) })
        await this.load()
      } catch (e) {
        console.error('设置默认地址失败', e)
        alert('设置默认地址失败，请稍后再试')
      }
    }
  }
}
</script>


